<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Contacts as ContactsModel;
use addons\qingdongams\model\ContactsFile;
use addons\qingdongams\model\ContactsOther;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\FormField;
use addons\qingdongams\model\Mobilecode;
use addons\qingdongams\model\Person;
use addons\qingdongams\model\OperationLog;
use addons\qingdongams\model\Staff;
use think\Db;
use think\Exception;
/**
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
/**
 * 联系人接口
 */
class Contacts extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//创建联系人
	public function addContacts() {
		$params = $this->request->post();
		if (empty($params['contacts'])) {
			$this->error('联系人信息不能为空');
		}
		// 表单验证
		if (($result = $this->qingdongamsValidate($params['contacts'],get_class(), 'create')) !== true) {
			$this->error($result);
		}
        $mobile =$params['contacts']['mobile']??'';
        $email =$params['contacts']['email']??'';
        if($mobile){
            if (ContactsModel::where([
                'customer_id'=>$params['contacts']['customer_id'],
                'mobile'      => $mobile,
            ])->find()) {
                $this->error('联系人手机号已存在');
            }
        }

        $result = FormField::checkFields(FormField::CONTACTS_TYPE,$params['contacts']);
        if ($result !== true) {
            $this->error($result);
        }

		Db::startTrans();
		try {
            
			if(empty($mobile) && empty($email)){
				$this->error('手机号码和邮箱至少填写一项！');
			}
			$rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
			$rule2 = '^\d+$^';
			if (preg_match($rule2, $mobile) ==false) {
				$this->error('手机号格式错误');
			}
			ContactsModel::createContacts($params['contacts']);
			$personModel = new Person();
            if($personId = $personModel->where(['account'=>$mobile])->value('id')){
                $personModel->where('id',$personId)->update(['customer_id'=>$params['contacts']['customer_id']]);
            }
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('创建联系人成功');
		}
	}


	//编辑联系人
	public function editContacts() {
		$id     = input('id');
		$params = $this->request->post();
		$row    = ContactsModel::where(['id' => $id])->find();
		if (empty($row)) {
			$this->error('客户信息不存在');
		}
		// 表单验证
		if (($result = $this->qingdongamsValidate($params,get_class(), 'edit')) !== true) {
			$this->error($result);
		}
		if (ContactsModel::where([
			'mobile'      => $params['mobile'],
			'customer_id' => $row['customer_id'],
			'id'          => ['neq', $params['id']]
		])->find()) {
			$this->error('联系人手机号已存在');
		}
        $result = FormField::checkFields(FormField::CONTACTS_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
		Db::startTrans();
		try {
			ContactsModel::updateContacts($params);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}

		$this->success('编辑联系人成功');
	}

    //姓名是否重复
    public function isNameDuplicate(){
        $name=input('name');
       $contacts= ContactsModel::where(['name'=>$name])->with('customer')->find();
       if(!empty($contacts)){
           $this->error('联系人名称已存在于客户【'.$contacts['customer']['name'].'】名下');
       }
       $this->success('不重复');
    }

	//删除联系人
	public function delContacts() {
		$id = input('id');

		$row = ContactsModel::where(['id' => $id, 'owner_staff_id' => $this->auth->id])->find();
		if (empty($row)) {
			$this->error('您不是客户归属人，无法删除当前联系人');
		}
		$model = new ContactsModel();
		if ($model->destroy(['id' => $id])) {
			$this->success('删除成功');
		}
		OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $row['customer_id'], '删除联系人:' . $row['name']);
		$this->error('删除失败');
	}


	//获取联系人列表
	public function getList() {
		$limit       = input("limit/d", 10);
		$customer_id = input('customer_id');
		$name        = input('name');
        $params = $this->request->post();

        $where= FormField::updateWhereField(FormField::CONTACTS_TYPE,$params);
		if ($customer_id) {
			$where['customer_id'] = $customer_id;
		}
		if ($name) {
			$where['name|mobile|telephone'] = ['like', "%{$name}%"];
		}
        if (isset($params['createtime']) && $params['createtime']) {//创建时间
            $createtime = $params['createtime'];
            $times = setTimes($createtime, 'time');
            $where['createtime'] = ['between', $times];
        }
        //0全部 1 我负责  2 下属负责的
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['owner_staff_id'] = $params['staff_id'];
        } else {
            $type = $params['type'] ?? 0;
            if ($type == 1) {//我负责的
                $where['owner_staff_id'] = $this->auth->id;
            } elseif ($type == 2) {//下属负责的
                $where['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
            }else{
                $where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
            }
        }
		$records                 = ContactsModel::where($where)->with(['customer'])->order('id desc')->paginate($limit);
    
        $this->success('请求成功', $records);
	}


	//获取select联系人列表
	public function getSelectList() {
		$customer_id = input('customer_id');
		$name = input('name');
		$where       = [];
		if ($customer_id) {
			$where['customer_id'] = $customer_id;
		}
		if ($name) {
			$where['name'] = ['like',"%{$name}%"];
		}
        $where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
		$list                    = ContactsModel::where($where)->field('id,name,mobile,mobilecode,region')->select();
		$list                    = collection($list)->toArray();
		foreach ($list as $k => $v) {
			$v['new_mobile'] = $v['mobile'];
			$list[$k]        = $v;
		}
		$this->success('请求成功', $list);
	}


	//获取联系人详情
	public function getDetail() {
		$id       = input('id');
        $ContactsModel=new ContactsModel();
		$contract = $ContactsModel->get(['id' => $id],[
            'customer',
            'ownerStaff'
        ]);
		if (empty($contract)) {
			$this->error('信息不存在');
		}
        $mobile= $contract->getData('mobile');
		$contract               = $contract->toArray();
        $contract['mobile']=$mobile;
        $contract['mobilecode_detail']= Mobilecode::where(['number'=>$contract['mobilecode']])->find();
        $contract=ContactsOther::getOther($contract);

		$this->success('请求成功', $contract);
	}


	//获取附件列表
	public function getFilesList() {
		$id = input('contacts_id');

		$files = ContactsFile::where(['contacts_id' => $id])->field('file_id')->with(['file'])->select();
		$this->success('请求成功', $files);
	}

	//获取国外电话区号
    public function getMobileCode() {
        $name       = input('name');
        $where =[];
        if(isset($name) && !empty($name)){
            $where['name|number'] = ['like','%'.$name.'%'];
        }
        $list = Mobilecode::where($where)->orderRaw('CONVERT(name using gbk) asc')->select();
        $this->success('',$list);

    }

    // 获取邮箱列表
    public function getEmails() {
        $name = input('name','');
        $where['email'] = [['not null',''],['neq',''],'and'];
        if(isset($name) && $name){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $list = \addons\qingdongams\model\Contacts::where($where)->field('id,name,email')->select();
        $this->success('',$list);
    }

}
